package com.ricchieri.lazymodel;

import java.util.List;
import java.util.Map;

import org.primefaces.model.LazyDataModel;
import org.primefaces.model.SortOrder;

import com.ricchieri.common.BusinessSettings;
import com.ricchieri.filter.CharterFilter;
import com.ricchieri.model.Charter;
import com.ricchieri.service.interf.ICharterService;

public class CharterLazyDataModel extends LazyDataModel<Charter> {
	
	private static final long serialVersionUID = 4597910900120000180L;
	
	private List <Charter> charters;
	private CharterFilter charterFilter;
	private ICharterService charterService;
	
	public CharterLazyDataModel(ICharterService charterService, CharterFilter charterFilter) {
		super();
		this.charterFilter = charterFilter;
		this.charterService = charterService;
	}
	
	@Override
	public List<Charter> load(int startingAt, int maxPerPage, String sortField, 
			SortOrder sortOrder, Map<String, String> filters) {
		
		charterFilter.setSortField(sortField);
		charterFilter.setSortOrder(sortOrder.toString());
		
        if(getRowCount() <= 0) {
            setRowCount(getCharterService().getAllCharterCountByFilter(charterFilter));
        }
        
        if(getRowCount() == startingAt && getRowCount()  != 0) {
        	startingAt = startingAt - BusinessSettings.ROW_MAX_RESULT;
        }
		charters = getCharterService().getAllCharterPaginatedByFilter(charterFilter, startingAt);

        setPageSize(BusinessSettings.ROW_MAX_RESULT);
        
        return charters;
	}
	
    @Override
    public Object getRowKey(Charter charter) {
        return charter.getId();
    }

    @Override
    public Charter getRowData(String charterId) {
        int id = Integer.valueOf(charterId);

        for (Charter charter : charters) {
            if(id == charter.getId()) {
                return charter;
            }
        }
        return null;
    }

	public List<Charter> getCharters() {
		return charters;
	}

	public void setCharters(List<Charter> charters) {
		this.charters = charters;
	}

	public CharterFilter getCharterFilter() {
		return charterFilter;
	}

	public void setCharterFilter(CharterFilter charterFilter) {
		this.charterFilter = charterFilter;
	}

	public ICharterService getCharterService() {
		return charterService;
	}

	public void setCharterService(ICharterService charterService) {
		this.charterService = charterService;
	}
}